//
//  BangoUtils.m
//  Bango
//

#import "BangoUtils.h"
#import "BangoConstants.h"

@implementation BangoUtils

+(NSString *)getUTCDate:(NSDate *)localDate
{
	NSLog(@"> %s", __PRETTY_FUNCTION__);
	NSLog(@"localDate %@", localDate);
	NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
	NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
	[dateFormatter setTimeZone:timeZone];
	[dateFormatter setDateFormat:DATETIME_FORMAT];
	NSString *dateString = [dateFormatter stringFromDate:localDate];	
	
	[dateFormatter release];
	
	return dateString;
}

+(NSString *)getLocalDate:(NSDate *)localDate
{
	NSLog(@"> %s", __PRETTY_FUNCTION__);
	NSLog(@"localDate %@", localDate);
	NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
	[dateFormatter setDateFormat:DATETIME_FORMAT];
	NSString *dateString = [dateFormatter stringFromDate:localDate];
	
	[dateFormatter release];
	
	return dateString;
}


// encode the string -
// this string by mike chambers seems to be better than the apple methods 
// http://mesh.typepad.com/blog/2007/10/url-encoding-wi.html
// simple API that encodes reserved characters according to:
// RFC 3986
// http://tools.ietf.org/html/rfc3986
+(NSString *) urlencode: (NSString *) stringToEncode
{
    NSArray *escapeChars = [NSArray arrayWithObjects:@";" , @"/" , @"?" , @":" ,
							@"@" , @"&" , @"=" , @"+" ,
							@"$" , @"," , @"[" , @"]",
							@"#", @"!", @"'", @"(", 
							@")", @"*", @" ",nil];
	
    NSArray *replaceChars = [NSArray arrayWithObjects:@"%3B" , @"%2F" , @"%3F" ,
							 @"%3A" , @"%40" , @"%26" ,
							 @"%3D" , @"%2B" , @"%24" ,
							 @"%2C" , @"%5B" , @"%5D", 
							 @"%23", @"%21", @"%27",
							 @"%28", @"%29", @"%2A", @"%20", nil];
	
    int len = [escapeChars count];
	
    NSMutableString *temp = [stringToEncode mutableCopy];
	
    int i;
    for(i = 0; i < len; i++)
    {
		
        [temp replaceOccurrencesOfString: [escapeChars objectAtIndex:i]
							  withString:[replaceChars objectAtIndex:i]
								 options:NSLiteralSearch
								   range:NSMakeRange(0, [temp length])];
    }
	
	return [temp autorelease];
}

+(double)getRoundedLocation:(double)location {
	NSString *str = [NSString stringWithFormat:@"%.6f", location];
	double result = [str doubleValue];
	return result;
}

@end
